import tkinter as tk
from tkinter import messagebox, filedialog
from PIL import Image, ImageTk

LIGHT_YELLOW = "#FFFACD"
LIGHT_BROWN = "#E7BD6E"
LIGHT_BROWN_ACTIVE = "#D4A76A"
DARK_BROWN = "#6B4832"

def init_creation_screen(parent, items):
    """
    Initializes the creation screen for adding new pets to the collection.
    
    Args:
        parent (tk.Tk or tk.Frame): The parent widget where the creation screen will be embedded.
        items (list): A list of dictionaries, where each dictionary represents an item with keys 'id', 'name', 'item_type', and 'age'.
    
    Returns:
        None
    """
    for widget in parent.winfo_children():
        widget.destroy()

    main_frame = tk.Frame(parent, bg=LIGHT_YELLOW)
    main_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)

    tk.Label(
        main_frame,
        text="Add new pet",
        font=("SimHei", 16, "bold"),
        bg=LIGHT_YELLOW,
        fg=DARK_BROWN
    ).pack(pady=20)

    name_frame = tk.Frame(main_frame, bg=LIGHT_YELLOW)
    name_frame.pack(fill=tk.X, pady=5)
    tk.Label(name_frame, text="Name:", font=("SimHei", 12), bg=LIGHT_YELLOW, fg=DARK_BROWN).pack(side=tk.LEFT, padx=5)
    name_entry = tk.Entry(name_frame, font=("SimHei", 12))
    name_entry.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=5)

    type_frame = tk.Frame(main_frame, bg=LIGHT_YELLOW)
    type_frame.pack(fill=tk.X, pady=5)
    tk.Label(type_frame, text="Type(form Warrior,Assassin,Mage,Marksman,Support):", font=("SimHei", 12), bg=LIGHT_YELLOW, fg=DARK_BROWN).pack(side=tk.LEFT, padx=5)
    type_entry = tk.Entry(type_frame, font=("SimHei", 12))
    type_entry.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=5)

    age_frame = tk.Frame(main_frame, bg=LIGHT_YELLOW)
    age_frame.pack(fill=tk.X, pady=5)
    tk.Label(age_frame, text="Age:", font=("SimHei", 12), bg=LIGHT_YELLOW, fg=DARK_BROWN).pack(side=tk.LEFT, padx=5)
    age_entry = tk.Entry(age_frame, font=("SimHei", 12))
    age_entry.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=5)

    img_frame = tk.Frame(main_frame, bg=LIGHT_YELLOW)
    img_frame.pack(fill=tk.X, pady=15)
    tk.Label(img_frame, text="Pet Image:", font=("SimHei", 12), bg=LIGHT_YELLOW, fg=DARK_BROWN).pack(side=tk.LEFT, padx=5)
    
    selected_img_path = [None]
    
    preview_frame = tk.Frame(img_frame, bg=LIGHT_YELLOW)
    preview_frame.pack(side=tk.LEFT, padx=10)
    
    preview_label = tk.Label(preview_frame, text="No image selected", width=30, height=10, relief="solid", bg="white", fg=DARK_BROWN, font=("SimHei", 10))
    preview_label.pack()

    def browse_image():
        """
        Opens a file dialog to select a pet image, displays a preview,
        and stores the selected image path.
        """
        file_path = filedialog.askopenfilename(
            title="Select Pet Image",
            filetypes=[("Image files", "*.jpg *.jpeg *.png *.gif *.bmp")]
        )
        if file_path:
            selected_img_path[0] = file_path
            try:
                img = Image.open(file_path)
                
                max_width = 400
                max_height = 300
                
                img_width, img_height = img.size
                if img_width > max_width or img_height > max_height:
                    width_ratio = max_width / img_width
                    height_ratio = max_height / img_height
                    scale_factor = min(width_ratio, height_ratio)
                    
                    new_width = int(img_width * scale_factor)
                    new_height = int(img_height * scale_factor)
                    img = img.resize((new_width, new_height), Image.LANCZOS)
                
                photo = ImageTk.PhotoImage(img)
                preview_label.config(image=photo, text="", width=img.width, height=img.height, bg=LIGHT_YELLOW)
                preview_label.image = photo
            except Exception as e:
                messagebox.showerror("Error", f"Failed to load image: {str(e)}")
                selected_img_path[0] = None
    
    browse_btn = tk.Button(img_frame, text="Browse", command=browse_image,
                          bg=LIGHT_BROWN, fg=DARK_BROWN, font=("SimHei", 10, "bold"),
                          relief="solid", borderwidth=1, activebackground=LIGHT_BROWN_ACTIVE)
    browse_btn.pack(side=tk.LEFT, padx=5)

    btn_frame = tk.Frame(main_frame, bg=LIGHT_YELLOW)
    btn_frame.pack(pady=20)
    
    tk.Button(
        btn_frame,
        text="Return",
        command=lambda: back_to_selection(parent),
        bg=LIGHT_BROWN, fg=DARK_BROWN, font=("SimHei", 10, "bold"),
        relief="solid", borderwidth=1, activebackground=LIGHT_BROWN_ACTIVE,
        width=10, height=1
    ).pack(side=tk.LEFT, padx=10)
    
    tk.Button(
        btn_frame,
        text="Add",
        command=lambda: do_add(
            parent, items,
            name_entry.get(),
            type_entry.get(),
            age_entry.get(),
            selected_img_path[0]
        ),
        bg=LIGHT_BROWN, fg=DARK_BROWN, font=("SimHei", 10, "bold"),
        relief="solid", borderwidth=1, activebackground=LIGHT_BROWN_ACTIVE,
        width=10, height=1
    ).pack(side=tk.LEFT, padx=10)

def back_to_selection(parent):
    """
    Returns to the main selection screen from the creation screen.
    
    Args:
        parent (tk.Widget): The parent container widget to navigate from
    """
    from src.ui.tkinter.main_window import show_screen
    show_screen("selection")

def do_add(parent, items, name, pet_type, age_str, img_path):
    """
    Validates input and creates a new pet item with the provided details.
    
    Handles input validation, image processing and saving, and coordinates
    with the item manager to create and store the new pet entry.
    
    Args:
        parent (tk.Widget): The parent container widget
        items (list): List of existing pet items
        name (str): Name of the new pet
        pet_type (str): Type/category of the new pet
        age_str (str): Age of the new pet as string input
        img_path (str): Path to the selected image file (or None)
    
    Returns:
        None: Shows success/error messages via messagebox and navigates back on success
    """
    if not name or not pet_type:
        messagebox.showerror("Error", "do not skip")
        return None
    try:
        age = int(age_str)
        if age < 1:
            raise ValueError("age must up 0")
    except ValueError as e:
        messagebox.showerror("Error", f"age type erroe: {str(e)}")
        return None

    try:
        
        from src.core.item_manager import create_item  
        from src.core.id_generator import generate_unique_id
        import os
        tkinter_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        pet_images_dir = os.path.join(tkinter_dir, "pet_images")
        if not os.path.exists(pet_images_dir):
            os.makedirs(pet_images_dir)
        
        saved_img_path = None
        if img_path:
            try:
                new_item_id = generate_unique_id(items)
                img_extension = os.path.splitext(img_path)[1]
                saved_img_path = os.path.join(pet_images_dir, f"pet_{new_item_id}{img_extension}")
                
                from shutil import copy2
                copy2(img_path, saved_img_path)
            except Exception as e:
                messagebox.showerror("Error", f"Failed to save image: {str(e)}")
                return None
        
        success, msg = create_item(
            items=items,        
            name=name.strip(),   
            item_type=pet_type.strip(), 
            age=age,            
            image_path=saved_img_path
        )

        
        if success:
            messagebox.showinfo("success", msg)
            back_to_selection(parent)  
        else:
            messagebox.showerror("Error", msg)

    except ImportError:
        
        messagebox.showerror("Error", "do not find create_item ,check right")
    except Exception as e:
        messagebox.showerror("Error", f"Add flase: {str(e)}")